<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>5-07 亮度调节</title>
</head>
<body>
  <canvas id="c" width="1000" height="300" style="border: 1px solid #ccc;"></canvas>

  <script>
    const context = document.getElementById('c')
    const ctx = context.getContext('2d')

    const img = new Image()
    img.src = '../images/desert.jpg'

    img.onload = () => {
      ctx.drawImage(img, 10, 10)

      const imgData = ctx.getImageData(10, 10, 300, 200)

      let luminance = 60 // 调节参数

      // 变亮
      const brighten = ctx.createImageData(imgData)
      brighten.data.set(imgData.data)
      const brightenData = brighten.data

      for (var i = 0; i < brightenData.length; i += 4) {
        brightenData[i + 0] += luminance
        brightenData[i + 1] += luminance
        brightenData[i + 2] += luminance
      }

      ctx.putImageData(brighten, 340, 10)

      // 变暗
      const darken = ctx.createImageData(imgData)
      darken.data.set(imgData.data)
      const darkenData = darken.data

      for (var i = 0; i < darkenData.length; i += 4) {
        darkenData[i + 0] -= luminance
        darkenData[i + 1] -= luminance
        darkenData[i + 2] -= luminance
      }

      ctx.putImageData(darken, 670, 10)
    }
  </script>
</body>
</html>